//
//  WQStatusDAL.swift
//  sanwuWeibo
//
//  Created by 王先强 on 15/12/22.
//  Copyright © 2015年 王先强. All rights reserved.
//

import Foundation
/// 本地缓存数据时间
private let dateCacheTimeInterval: NSTimeInterval = 60 //* 60 * 24 * 7

class WQStatusDAL {
    
    //1.检查本地是否有缓存数据
    //2.如果有返回本地数据
    //3.如果没有,加载网络数据
    //4.将网络数据保存至本地
    //5.返回网络数据
    
    
    
    ///清除缓存数据
    class func clearDataCache() {
        
        let date = NSDate(timeIntervalSinceNow: -dateCacheTimeInterval)
        let dateFormat = NSDateFormatter()
        dateFormat.dateFormat = "yyyy-MM-dd HH:mm:ss"
        let dateStr = dateFormat.stringFromDate(date)
        print(dateStr)
        let sql = "delete from T_Status where createTime < ?;"
        SQLiteManager.sharedManager.queue.inDatabase { (db) -> Void in
            db.executeUpdate(sql, dateStr)
            print("删除来 \(db.changes()) 条记录")
        }
        
    }
    
    
    
    //加载网络数据
    class func loadStatus(since_id: Int, max_id: Int, finished:(array:[[String: AnyObject]]?) -> ()) {
        //检查本地缓存
        let array = WQStatusDAL.checkCacheData(since_id, max_id: max_id)
        if array?.count > 0 {
            print("有缓存数据,返回缓存数据\(array?.count)")
            finished(array: array)
            return
        }
        print("没有缓存数据,进行网络加载 \(array?.count)")
        WQNetTool.shareTool.loadStatus(WQAccountViewModel.sharedAccount.account!, since_id: since_id){ (success, failure) -> () in
            //加载网络数据
            if failure != nil {
                print("加载网络数据错误\(failure)")
                finished(array: nil)
                return
            }
            guard let statusArr = (success?["statuses"] as? [[String: AnyObject]]) else {
                print("返回数据解析错误")
                finished(array: nil)
                return
            }
            //成功获取数据，缓存数据
            saveCacheData(statusArr)
            //返回数据数组
            finished(array: statusArr)
        }
    }
    
    
    //检查本地数据缓存，有就返回数据数组，没有就返回nil
    private class func checkCacheData(since_id: Int, max_id: Int) -> [[String: AnyObject]]? {
        //1. 创建存放数据的数组
        var arrayM = [[String: AnyObject]]()
        //2. 获取账户字段
        guard let userId = WQAccountViewModel.sharedAccount.account?.uid else {
            return arrayM
        }
        //3.准备sql
        var sql = "select statusId, status, userId from T_Status\n"
        sql += "where userId = \(userId)\n"
        if since_id > 0 {//下拉刷新
            sql += "and statusId > \(since_id)\n"
        }else if max_id > 0 {//上拉刷新
            sql += "and statusId < \(max_id)\n"
        }
        //设置排序为降序排列，一次选择20条数据
        sql += "order by statusId desc limit 20;"
        
        //4.执行sql
        SQLiteManager.sharedManager.queue.inDatabase { (db) -> Void in
            //
            guard let resultSet = db.executeQuery(sql) else {
                return
            }
            
            while resultSet.next() {
                let data = resultSet.dataForColumn("status")
                let dict = try! NSJSONSerialization.JSONObjectWithData(data, options: [])
                arrayM.append(dict as! [String : AnyObject])
            }
            
            
        }
        return arrayM
    }
    
    
    ///  保存网络数据
    class func saveCacheData(array:[[String: AnyObject]]) {
        
        guard let userId = WQAccountViewModel.sharedAccount.account?.uid else {
            print("用户没有登录")
            return
        }
        // 1.SQL
        /**
            需要保存的参数
            1> 微博数据中时间id
            2> 单条微博数据的json数据
            3> 账户的userId
        */
        let sql = "insert or replace into T_Status (statusId, status, userId) values (?, ?, ?);"
        
        // 2.遍历数组，插入数据
        SQLiteManager.sharedManager.queue.inTransaction { (db, rollBack) -> Void in
            
            for dict in array {
                //获取微博id
                let statusId = dict["id"] as! Int
                let json = try! NSJSONSerialization.dataWithJSONObject(dict, options: [])
                if !db.executeUpdate(sql, statusId, json, userId) {
                    rollBack.memory = true
                    break
                }
            }
            
        }
        
    }
    
}